package com.qfedu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.dao.CustomerDao;
import com.qfedu.entity.Customerinfo;
import com.qfedu.service.CustomerService;
import com.qfedu.util.RandomStringUtil;
import com.qfedu.util.Result;
import com.qfedu.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * projectName: logistics
 * author: CGY
 * time: 2020/10/6 11:17
 * description:
 */
@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDao customerDao;
    private String str = "KH";
    private String getCode(){
        String code = null;
        while(true){
            String s = RandomStringUtil.RandString(6);
            code = str +  s;
            Customerinfo cus = customerDao.findByCustomerCode(code);
            if(cus == null){
                break;
            }
        }
        return code;
    }

    @Override
    public Result addCus(Customerinfo customerinfo) {
        String code = getCode();
        customerinfo.setCustomerCode(code);
        Customerinfo cus = customerDao.save(customerinfo);
        if(cus == null){
            return Result.error("添加失败");
        }
        return Result.success(cus);
    }

    @Override
    public PageInfo selectAllCus(Integer pageNum, Integer limit) {
        PageHelper.startPage(pageNum,limit);
        List<Customerinfo> list = customerDao.findAll();
        PageInfo<Customerinfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Result selectCusByCode(String customerCode) {
        Customerinfo cus = customerDao.findByCustomerCode(customerCode);
        if(cus == null){
            return Result.error("查询失败");
        }
        return Result.success(cus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteCus(String customerCode) {
        Customerinfo customer = customerDao.findByCustomerCode(customerCode);
        if(customer == null){
            return Result.error("账户不存在");
        }
        Integer row = customerDao.deleteByCustomerCode(customerCode);
        if(row <= 0){
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }

    @Override
    public Result updateCustomerInfo(Customerinfo customerinfo) {
        System.out.println("customerinfo = " + customerinfo);
        Customerinfo cus = customerDao.save(customerinfo);
        if(cus == null){
            return Result.error("更新失败");
        }
        return Result.success(cus);
    }

    @Override
    public Result selectAllCusCode() {
        List<Customerinfo> list = customerDao.findAll();
        return ResultUtil.getObject(list,"查询失败");
    }
}
